import java.io.File;
import java.io.FileOutputStream;

/*
 * User similarity based on number of votes.
 */
public class ANV extends Scheduler implements Runnable {
	int start;
	int stop;
	byte[] BLOCK;

	final double NONE = Double.NaN;

	public ANV(int start, int stop) {
		this.start = start;
		this.stop = stop;
	}

	void writeBlock() {
		String FILE_NAME = String.format("%s%07d.bin", BLOCK_PATH, start);
		File out = new File(FILE_NAME);
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(out);
			fos.write(BLOCK);
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("Done writing: " + FILE_NAME + " @ "
				+ this.getClass());
	}

	@Override
	public void run() {
		int ilen = USERB[0].ilen;
		BLOCK = new byte[(stop - start) * ilen];

		int c = 0;
		for (int bUserId = start; bUserId < stop; bUserId++) {
			for (int i = 0; i < ilen; i++) {
				int bItemId = USERB[bUserId].items[i];
				byte pred = predict(bUserId, bItemId);

				BLOCK[c * ilen + i] = pred;
			}
			c++;
		}
		writeBlock();
	}

	private byte predict(int bUserId, int bItemId) {
		Item bItem = ITEMA[bItemId];
		int nVotes = USERA[bUserId].ilen;
		double mostSimilar = Double.MAX_VALUE;
		double mostSimilarVote = USERA[bUserId].mean;
		for (int u = 0; u < bItem.ulen; u++) {
			double similarity = Math.abs(nVotes - USERA[bItem.users[u]].ilen);
			if (similarity < mostSimilar) {
				mostSimilar = similarity;
				mostSimilarVote = USERA[bItem.users[u]].getVoteHash(bItemId);
			}
		}
		return (byte) mostSimilarVote;
	}
}
